package hasthi.actuators.event;

import hasthi.common.constants.HasthiConstants;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * This class correlate events and trigger actions. May be later we need a CEP engine here. But for now this will only  trigger
 * registered callback with the given event. If the event is triggered before the callback, it will be lost.
 * @author hperera
 *
 */
public class EventCorrelator {
    private static Log log = LogFactory.getLog(HasthiConstants.LOGGER_NAME);
    private Map<String, EventCallback> eventMap = new ConcurrentHashMap<String, EventCallback>();
    public void triggerEvent(HasthiEvent event){
        log.debug("Event Occuered "+ event );
        EventCallback eventCallback = eventMap.get(event.getName());
        if(eventCallback != null){
            eventCallback.eventOccuered(event);
            if(eventCallback.isOneTimeOnly()){
                //if it is a one time only event, remove it
                eventMap.remove(event.getName());
            }
        }else{
            log.warn("Event Ignored "+ event);
        }
    }
    
    public void registerCallback(String eventname,EventCallback callback){
        log.debug("Event callback registered "+ eventname + "["+callback + "]");
        eventMap.put(eventname, callback);
    }
}
